﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FieldTools.Util.Helper
{
    /// <summary>
    /// 身份证帮助类
    /// </summary>
    public static class IdentityCardHelper
    {
        public static readonly string[] CheckCode = { "1","0","x","9","8","7","6","5","4","3","2"};
        public static readonly int[] MulCoefficient = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
        /// <summary>
        /// 创建一个符合规则的随机身份证
        /// </summary>
        /// <param name="code">地区行政代码</param>
        /// <param name="date">出生日期(yyyyMMdd)</param>
        /// <param name="sex">性别，0男，1女</param>
        /// <param name="generation">第几代身份证</param>
        /// <returns></returns>
        public static string CreatIdentityCardNo(string code, string date, int sex, int generation = 2)
        {
            if (sex < 0 || sex > 1)
            {
                throw new ArgumentException("性别代码出错");
            }
            if(generation < 1 || generation >2)
            {
                throw new ArgumentException("目前仅仅支持第一、二代身份证，检查参数是否传递错误");
            }
            if(code.Length != 6)
            {
                throw new ArgumentException("行政区域代码不合法");
            }
            //性别码，忽略顺序
            int r = RandomHelper.Next(0, 10);
            r = r % 2 != sex ?( r >=9 ? r - 1: r + 1):r;
            int r0 = RandomHelper.Next(0, 100);
            if(generation == 1)
            {
                var ls = date.ToList();
                ls.RemoveRange(0, 2);
                var da = "";
                ls.ForEach(x =>
                {
                    da += x.ToString();
                });
                return code + da + r0.ToString("00") + r.ToString();
            }
            string idNo0 = code + date + r0.ToString("00") + r.ToString();
            //校验码
            string checkCode = GetCheckCode(idNo0);
            //身份证号
            string idNo = idNo0 + checkCode;
            return idNo;
        }
        /// <summary>
        /// 校验身份证是否合法
        /// </summary>
        /// <param name="idNo">身份证号</param>
        /// <returns></returns>
        public static bool CheckIdentityCardNo(string idNo)
        {
            if (idNo.Length == 18)
            {

                bool check = CheckIDCard18(idNo);
                return check;
            }
            else if (idNo.Length == 15)
            {
                bool check = CheckIDCard15(idNo);
                return check;
            }
            else
            {
                return false;
            }
        }

        public static string GetCheckCode(string idNoZ)
        {
            if(idNoZ.Length < 17)
            {
                throw new ArgumentException("至少17位数字字符串才可计算校验位");
            }
            int sum = 0;
            for(int i = 0; i < 17; i++)
            {
                sum += idNoZ[i].ToString().ToInt() * MulCoefficient[i];
            }
            return CheckCode[sum % 11];
        }

        /// <summary>
        /// 18位身份证号码验证
        /// </summary>
        /// <param name="idNumber"></param>
        /// <returns></returns>
        public static bool CheckIDCard18(string idNumber)
        {
            long n = 0;
            if (long.TryParse(idNumber.Remove(17), out n) == false
                || n < Math.Pow(10, 16) || long.TryParse(idNumber.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证  
            }

            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(idNumber.Remove(2)) == -1)
            {
                return false;//省份验证  
            }

            string birth = idNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证  
            }

            string[] arrVarifyCode = CheckCode;
            int[] Wi = MulCoefficient;
            char[] Ai = idNumber.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += Wi[i] * int.Parse(Ai[i].ToString());
            }

            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != idNumber.Substring(17, 1).ToLower())
            {
                return false;//校验码验证 
            }

            return true;//符合GB11643-1999标准 
        }

        /// <summary>
        /// 15位身份证号码验证
        /// </summary>
        /// <param name="idNumber"></param>
        /// <returns></returns>
        public static bool CheckIDCard15(string idNumber)
        {

            long n = 0;
            if (long.TryParse(idNumber, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证
            }

            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(idNumber.Remove(2)) == -1)
            {
                return false;//省份验证  
            }

            string birth = idNumber.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证  
            }
            return true;
        }
    }
}
